import { messages, queryCurrencyPrecision } from "share/common";
import React from 'react'
import { Modal, Row, Col, Switch, Icon, Spin, Tooltip, Popover, Tag, Collapse, Divider } from 'antd'
import financeAuditService from './finance-audit.service'
import 'styles/financial-management/finance-audit/file-audit.scss'
import FileViewer from "components/file-viewer";
import constants from 'share/constants'
import ColumnLayout from 'components/template/slide-document/column-layout'
import checkedImg from 'images/financial-management/file-audit/checked.png'
import ReactDOM from "react-dom";

const { ColumnLayoutLeft, ColumnLayoutRight } = ColumnLayout;
const { Panel } = Collapse;

class FileAudit extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      invoices: [],
      nowInvoiceIndex: 0,
      nowAttachmentIndex: 0,
      totalAttachments: 0,
      checking: false,
      change: false,
      activeKey: 0,
      modalParams: null
    };
    this.flag = 0;
  }

  componentDidMount(){
    if (window.addEventListener) {
      window.addEventListener('keyup', this.handleKeyUp);
    } else {
      window.attachEvent('onkeyup', this.handleKeyUp);
    }
  }

  componentWillReceiveProps(nextProps){
    const { invoices, visible, defaultImage } = nextProps;
    //显示时初始化
    if(visible && !this.props.visible){
      let result = [];
      let totalAttachments = 0;
      let nowInvoiceIndex = 0, nowAttachmentIndex = 0;

      invoices.map(invoice => {
        let allChecked = true;
        let target = invoice;
        invoice.receiptList.map(invoice => {
          let attachment =  invoice.slicingAttachment || invoice.originAttachment;
          if(invoice.originAttachment && invoice.originAttachment.fileType.toUpperCase() === 'PDF') {
            attachment = invoice.originAttachment;
          }
          attachment && target.attachments.addIfNotExistObj(attachment, 'id');
        });
        if(target.attachments && target.attachments.length > 0){
          target.attachments.map(attachment => {
            allChecked = allChecked && attachment.checked;
          });
          target.allChecked = allChecked;
          result.push(target);
          totalAttachments += target.attachments.length;
        }
      });
      result.map((invoice, invoiceIndex) => {
        invoice.attachments.map((attachment, attachmentIndex) => {
          if(defaultImage && defaultImage.attachmentOID === attachment.attachmentOID){
            nowInvoiceIndex = invoiceIndex;
            nowAttachmentIndex = attachmentIndex;
          }
        });
      });
      this.setState({
        invoices: result,
        activeKey: nowInvoiceIndex,
        totalAttachments,
        nowInvoiceIndex,
        nowAttachmentIndex
      });
    }
  }

  componentDidUpdate() {
    setTimeout(() => {
      this.dom = ReactDOM.findDOMNode(this.refs.fileAuditRefs);
      this.dom && !this.flag && this.setState({
        modalParams: {
          mask: false,
          getContainer: () => this.dom.querySelector(".invoice-preview-box"),
          wrapClassName: 'invoice-wrapped-box',
          width: '100%',
          closable: false,
          keyboard: false
        }
      }, () => this.flag = 1)
    }, 200);
  }

  componentWillUnmount(){
    if (window.addEventListener) {
      window.removeEventListener('keyup', this.handleKeyUp);
    } else {
      window.detachEvent('onkeyup', this.handleKeyUp);
    }
  }

  //键盘事件
  handleKeyUp = (e) => {
    e.stopPropagation();
    let { nowAttachmentIndex, nowInvoiceIndex, invoices } = this.state;
    const { visible, isEnableCheck } = this.props;
    if(visible){
      switch(e.keyCode){
        //空格
        case 32: {
          if (isEnableCheck) {
            this.handleCheckAttachment(!invoices[nowInvoiceIndex].attachments[nowAttachmentIndex].checked  ,nowInvoiceIndex, nowAttachmentIndex)
          }
          break;
        }
        //⬅
        case 37: {
          if(nowAttachmentIndex !== 0)
            this.handleSelectAttachment(--nowAttachmentIndex);
          break;
        }
        //⬆
        case 38:{
          if(nowInvoiceIndex !== 0)
            this.handleSelectInvoice(--nowInvoiceIndex);
          break;
        }
        //➡
        case 39:{
          if(nowAttachmentIndex !== invoices[nowInvoiceIndex].attachments.length - 1)
            this.handleSelectAttachment(++nowAttachmentIndex);
          break;
        }
        //⬇
        case 40:{
          if(nowInvoiceIndex !== invoices.length - 1)
            this.handleSelectInvoice(++nowInvoiceIndex);
          break;
        }
      }
    }
  };

  //审核图片
  handleCheckAttachment = (checked, invoiceIndex, attachmentIndex) => {
    let { invoices, nowInvoiceIndex } = this.state;
    this.setState({ checking: true });
    financeAuditService.checkAttachment({
      attachmentOID: invoices[invoiceIndex].attachments[attachmentIndex].attachmentOID,
      checked,
      invoiceOID: invoices[invoiceIndex].invoiceOID,
    }).then(res => {
      invoices[invoiceIndex].attachments[attachmentIndex].checked = checked;
      let allChecked = true;
      invoices[invoiceIndex].attachments.map(attachment => {
        allChecked = allChecked && attachment.checked;
      });
      invoices[invoiceIndex].allChecked = allChecked;
      this.setState({ invoices, checking: false, nowInvoiceIndex, change: true });
      this.props.onAuditChange(invoices)
    });
  };

  handleSelectAttachment = (index) => {
    this.setState({ nowAttachmentIndex: index });
  };

  handleSelectInvoice = (index) => {
    this.setState({ activeKey: index });
    if(typeof index !== 'undefined') {
      this.setState({ nowInvoiceIndex: index, nowAttachmentIndex: 0 });
    }
  };

  renderMessageKeyFields = invoice => {
    return invoice.data
      .filter(field => constants.targetMessageKeys[field.messageKey])
      .map(field => {
        const target = constants.targetMessageKeys[field.messageKey];
        return (
          <Row>
            <Col span={4}>{target.title}:</Col>
            <Col span={20}>{target.render(field)}</Col>
          </Row>
        )
      })
  };

  renderLeftContent = () => {
    const { totalAttachments, invoices, activeKey } = this.state;
    const { info, isEnableCheck, onCancel } = this.props;
    let allCheckedNumber = invoices.filter(invoice => !!invoice.allChecked).length;
    const infoContent = (
      <div>
        {`1. ${messages('expense-14.key207')/*此模式下只显示该单据下所有含有发票原件/发票图片/附件的费用*/}；`}<br/>
        {`2. ${messages('expense-14.key208')/*此模式下仅可查看jpg/png/pdf/excel/word/ppt/txt文件*/}；`}<br/>
        {`3. ${messages('expense-14.key209')/*键盘↔️可切换图片/文件，↕️切换费用*/}${isEnableCheck ? `，
             ${messages('expense-14.key210')/*按【空格】标记已核对/未核对*/}；` : '；'}`}<br/>
        {`4. ${messages('expense-14.key211')/*此模式可通过发票图片/发票原件/附件缩略图点击进入*/}；`}<br/>
        {`5. ${messages('expense-14.key212')/*基于各个浏览器兼容性，部分格式文件点击下载按钮，将打开新浏览页，请在新页面右击另存为*/}`}
      </div>
    );
    return (
      <div className='file-audit-left-content'>
        <div className='file-audit-left-content-back'>
          <span onClick={() => onCancel()}>
           <Icon type='left' /> {messages('common.back')/*返回*/}
          </span>
        </div>
        <div className='file-audit-left-content-title'>
          <p>
            {info && <span>{info.formName}:{info.parentBusinessCode ? `${info.parentBusinessCode}-` : ''}{info.businessCode}</span>}
          </p>
          <p>
            {isEnableCheck ?
              messages('expense-14.key213')/*发票及附件审核*/ :
              messages('expense-14.key214')/*发票及附件查看*/}
            {messages('common.total',{arg1: totalAttachments})/*共搜索到 {arg1} 条数据*/}
            <Tooltip title={infoContent} placement="bottomLeft">
              <Icon type="info-circle-o" />
            </Tooltip>
          </p>
        </div>
        {isEnableCheck && (
          <div className="file-audit-left-content-count">
            {messages('expense-14.key215')/*待核对费用*/}
            <span>{invoices.length - allCheckedNumber}</span>
            {messages('expense-14.key216')/*笔*/}
          </div>
        )}
        <div className="file-audit-left-content-expense-container">
          <Collapse
            accordion
            activeKey={`${activeKey}`}
            onChange={this.handleSelectInvoice}
          >
            {invoices.map((invoice, index) => (
              <Panel
                key={`${index}`}
                className='file-audit-left-content-expense-container-item'
                header={
                  <Row>
                    <Col span={6}>
                      <Popover
                        content={new Date(invoice.createdDate).format('yyyy-MM-dd')}
                      >
                        {new Date(invoice.createdDate).format('yyyy-MM-dd')}
                      </Popover>
                    </Col>
                    <Col span={10}>
                      <Popover content={invoice.expenseTypeName}>{invoice.expenseTypeName}</Popover>
                    </Col>
                    <Col span={4}>
                      <span>{invoice.invoiceCurrencyCode}</span>
                    </Col>
                    <Col span={4}>
                      <Popover
                        content={this.filterMoney(invoice.amount,queryCurrencyPrecision(invoice.invoiceCurrencyCode))}
                      >
                        {this.filterMoney(invoice.amount,queryCurrencyPrecision(invoice.invoiceCurrencyCode))}
                      </Popover>
                    </Col>
                    {(invoice.allChecked && isEnableCheck) && <img src={checkedImg} className='checked-expense-icon' />}
                  </Row>
                }
              >
                <Row>
                  <Col span={4}>{messages('expense-14.key217')/*事由说明temp*/}:</Col>
                  <Col span={20}>{invoice.comment || '-'}</Col>
                </Row>
                <Row>
                  <Col span={4}>{messages('expense-14.key218')/*摘要*/}:</Col>
                  <Col span={20}>{(invoice.summaryInfo || '').replace(/&#13;/g, ' ') || '-'}</Col>
                </Row>
                {this.renderMessageKeyFields(invoice)}
                {invoice.invoiceLabels && (
                  <Row className='invoice-expand-label'>
                    {invoice.invoiceLabels.map(item => {
                      let result = '';
                      if (item.level === 'WARN') {
                        result = <Tag color="yellow" style={{marginTop: '3px'}}>{item.name}</Tag>;
                      }
                      if (item.level === 'ERROR') {
                        result = <Tag color="red" style={{marginTop: '3px'}}>{item.name}</Tag>;
                      }
                      if(item.level === 'INFO') {
                        result = <Tag color="blue" style={{marginTop: '3px'}}>{item.name}</Tag>;
                      }
                      return item.toast ? <Tooltip title={item.toast.split('&#13;').map(record => <div>{record}</div>)} placement="topLeft">{result}</Tooltip> : result;
                    })}
                  </Row>)
                }
                {
                  invoice.receiptList && invoice.receiptList.map((item, index) => {
                    return (
                      <div key={index}>
                        <Row>
                          <Col span={4}>{messages('common.invoice.type')/*发票类型*/}:</Col>
                          <Col span={20}>{item.type}</Col>
                        </Row>
                        <Row>
                          <Col span={4}>{messages('expense-14.key172')/*发票代码*/}:</Col>
                          <Col span={8} style={{paddingRight: '3px'}}>{item.billingCode}</Col>
                          <Col span={4}>{messages('expense-14.key173')/*发票号码*/}:</Col>
                          <Col span={8}>{item.billingNo}</Col>
                        </Row>
                        <Row>
                          <Col span={4}>{messages('expense-14.key187')/*开票日期*/}:</Col>
                          <Col span={20}>{item.billingTime ? new Date(item.billingTime * 1000).format('yyyy-MM-dd') : ''}</Col>
                        </Row>
                        <Row>
                          <Col span={4}>{messages('expense-14.key192')/*金额合计*/}:</Col>
                          <Col span={8} style={{paddingRight: '3px'}}>{typeof item.feeWithoutTax === 'number' ? (item.feeWithoutTax / 100).toFixed(queryCurrencyPrecision()) : '-'}</Col>
                          <Col span={4}>{messages('expense-14.key191')/*税额合计*/}:</Col>
                          <Col span={8}>{typeof item.tax === 'number' ? ((item.tax) / 100).toFixed(queryCurrencyPrecision()) : '-'}</Col>
                        </Row>
                        <Row>
                          <Col span={4}>{messages('expense-14.key189')/*价税合计*/}:</Col>
                          <Col span={20}>{typeof item.fee === 'number' ? ((item.fee) / 100).toFixed(queryCurrencyPrecision()) : '-'}</Col>
                        </Row>
                      </div>
                    )
                  })
                }
              </Panel>
            ))}
          </Collapse>
        </div>
      </div>
    )
  };
  renderRightContent = () => {
    const { invoices, nowInvoiceIndex, nowAttachmentIndex, checking, modalParams } = this.state;
    const { isEnableCheck } = this.props;
    let nowInvoice = invoices[nowInvoiceIndex];
    let attachments = nowInvoice ? nowInvoice.attachments : [];
    let attachment = attachments.length > 0 ? attachments[nowAttachmentIndex] : {};
    return (
      <div className='file-audit-right-content' ref='fileAuditRefs'>
        {nowInvoice &&
          <div>
            <div className="file-audit-right-content-title">
              <span>
                {nowInvoice.expenseTypeName}&nbsp;&nbsp;
                {nowInvoice.invoiceCurrencyCode}
                {nowInvoice.amount.toFixed(queryCurrencyPrecision(nowInvoice.invoiceCurrencyCode))}
              </span>
              <span className='file-audit-right-content-subtitle'>
                {messages('common.attachments')/*附件*/}
                {nowAttachmentIndex + 1}/
                {invoices[nowInvoiceIndex].attachments.length}
              </span>
            </div>
            <div className='invoice-preview-box'>
              {modalParams && <FileViewer
                visible={true}
                markable={isEnableCheck}
                modalParams={modalParams}
                attachments={attachments}
                defaultIndex={nowAttachmentIndex}
                onClick={this.handleSelectAttachment}
                urlKey="fileURL"
                valueKey="id"
                markKey='checked'
                extraOption={() => <span>
                  {
                    isEnableCheck && (
                      <span>
                        <Divider type="vertical" />
                        <Spin spinning={checking} wrapperClassName='file-audit-right-content-check'>
                          <Switch
                            size="small"
                            checked={attachment.checked}
                            onChange={checked => this.handleCheckAttachment(checked, nowInvoiceIndex, nowAttachmentIndex)}
                          />
                          <span className="attachment-status-description">
                            {attachment.checked ?
                              messages('expense-14.key17')/*已核对*/ :
                              messages('expense-14.key219')/*未核对*/
                            }
                          </span>
                        </Spin>
                      </span>)
                  }
                </span>}
              />}
            </div>
          </div>}
      </div>
    )
  };

  render() {
    const { visible, onCancel, afterClose } = this.props;
    return (
      <Modal
        className="file-audit"
        visible={visible}
        footer={null}
        onCancel={() => onCancel()}
        afterClose={afterClose}
        width='100%'
        closable={false}
      >
        <ColumnLayout leftWidth={420}>
          <ColumnLayoutLeft>{this.renderLeftContent()}</ColumnLayoutLeft>
          <ColumnLayoutRight>{this.renderRightContent()}</ColumnLayoutRight>
        </ColumnLayout>
      </Modal>
    )
  }
}

FileAudit.propTypes = {
  visible: React.PropTypes.bool.isRequired,
  invoices: React.PropTypes.array.isRequired,
  afterClose: React.PropTypes.func,
  onCancel: React.PropTypes.func,
  defaultImage: React.PropTypes.any,
  isEnableCheck: React.PropTypes.bool, //是否启用核对功能
  onAuditChange: React.PropTypes.func //图片审核后的回调
};

FileAudit.defaultProps = {
  visible: false,
  defaultImage: null,
  isEnableCheck: false,
  afterClose: () => {}
};

export default FileAudit
